<template>
  <div class="register">
    <div class="container">
      <h2>注册</h2>
      <el-form
        class="form"
        ref="registerForm"
        :model="registerForm"
        :rules="rules"
        label-width="60px"
        hide-required-asterisk
      >
        <el-form-item prop="username">
          <span slot="label">用户名</span>
          <el-input v-model="registerForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item prop="password">
          <span slot="label">密码</span>
          <el-input v-model="registerForm.password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form>
          <el-button type="primary" :loading="isButtonLoading" plain @click="handleRegister">注册</el-button>
          <el-button type="success" plain @click="goLogin">已有账号，前往登录</el-button>
        </el-form>
      </el-form>
    </div>
  </div>
</template>

<script>
import { register } from '@/api/user'
import { formatDateTime } from '@/utils/dateUtil'
export default {
  name: 'Register',
  data() {
    return {
      registerForm: {
        username: '',
        password: '',
        createDate: ''
      },
      rules: {
        username: [
          {
            message: '请输入用户名',
            required: true,
            trigger: 'blur'
          }
        ],
        password: [
          {
            message: '请输入密码',
            required: true,
            trigger: 'blur'
          }
        ]
      },
      isButtonLoading: false
    }
  },
  methods: {
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.registerForm.createDate = formatDateTime(new Date())
          this.isButtonLoading = true
          register(this.registerForm).then(res => {
            this.isButtonLoading = false
            this.goLogin()
          }, err => {
            this.isButtonLoading = false
            console.log(err)
          })
        }
      })
    },
    goLogin() {
      this.$router.push({
        path: '/login'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.register {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  background: url("../..//assets/images/background.jfif") no-repeat;
  background-size: cover;
  background-attachment: fixed;
  .container {
    width: 500px;
    border-radius: 5px;
    padding: 0 30px 30px 30px;
    background-color: #ffffff7d;
    box-shadow: 0 0 10px #bebebe;
    .form {
      span {
        color: white;
      }
    }
    h2 {
      text-align: center;
      margin: 20px 0;
    }
    .el-button {
      width: 48%;
    }
  }
}
</style>
